package at.guthy;

import java.awt.Component;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import com.google.gdata.data.photos.AlbumEntry;

public class PicasaPicturesTable extends JTable implements DropTargetListener {
	private static PicasaTableModel tableModel = new PicasaTableModel();

	public PicasaPicturesTable() {
		super(tableModel);
		this.setDragEnabled(true);
		// DropTarget dropTarget = new DropTarget(this, this);

		System.out.println(this.getColumnName(0));

		this.setRowHeight(52);
		this.getColumn("thumbnail").setCellRenderer(new PhotoThumbnailRenderer());
	}

	public void reload(AlbumEntry selectedAlbum) {
		try {
			tableModel.reload(selectedAlbum.getFeedLink().getHref());
		}
		catch (NullPointerException e) {
			
		}

	}

	@Override
	public void dragEnter(DropTargetDragEvent arg0) {}

	@Override
	public void dragExit(DropTargetEvent arg0) {}

	@Override
	public void dragOver(DropTargetDragEvent arg0) {}

	@Override
	public void drop(DropTargetDropEvent e) {
		try {
			Transferable tr = e.getTransferable();
			for (DataFlavor f : tr.getTransferDataFlavors()) {
				System.out.println(f.toString());
			}

			if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
				e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

				File[] files = (File[]) tr.getTransferData(DataFlavor.javaFileListFlavor);
				tr.getTransferData(DataFlavor.javaFileListFlavor);
				Thread uploader = new UploaderThread(files);
				uploader.start();

				e.getDropTargetContext().dropComplete(true);
			}
			else {
				System.err.println("DataFlavor.javaFileListFlavor is not supported, rejected");
				e.rejectDrop();
			}
		}
		catch (IOException ex) {
			System.err.println("IOException");
			ex.printStackTrace();
			e.rejectDrop();
		}
		catch (UnsupportedFlavorException ex) {
			System.err.println("UnsupportedFlavorException");
			ex.printStackTrace();
			// e.rejectDrop();
		}
	}

	@Override
	public void dropActionChanged(DropTargetDragEvent arg0) {}
}

class PhotoThumbnailRenderer extends DefaultTableCellRenderer {

	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		// ImageIcon icon = new ImageIcon(new java.net.URL((ImageIcon) value));
		setIcon((ImageIcon) value);
		return this;
	}
}